package com.service;

import com.alibaba.fastjson.JSON;
import com.config.DeepSeekConfig;
import com.entity.DeepSeekRequest;
import com.entity.DeepSeekResponse;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * DeepSeek API 服务类
 */
@Service
public class DeepSeekService {
    
    private static final Logger logger = LoggerFactory.getLogger(DeepSeekService.class);
    
    @Autowired
    private DeepSeekConfig deepSeekConfig;
    
    private final OkHttpClient httpClient;
    
    public DeepSeekService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
    }
    
    /**
     * 发送聊天请求到DeepSeek
     * @param userMessage 用户消息
     * @param systemPrompt 系统提示词（可选）
     * @return DeepSeek响应
     */
    public DeepSeekResponse chat(String userMessage, String systemPrompt) {
        try {
            // 构建请求消息
            DeepSeekRequest request = new DeepSeekRequest();
            request.setModel(deepSeekConfig.getModel());
            request.setTemperature(0.7);
            request.setMaxTokens(2000);
            request.setStream(false);
            
            if (systemPrompt != null && !systemPrompt.isEmpty()) {
                request.setMessages(Arrays.asList(
                    new DeepSeekRequest.Message("system", systemPrompt),
                    new DeepSeekRequest.Message("user", userMessage)
                ));
            } else {
                request.setMessages(Arrays.asList(
                    new DeepSeekRequest.Message("user", userMessage)
                ));
            }
            
            // 构建HTTP请求
            String json = JSON.toJSONString(request);
            RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
            
            Request httpRequest = new Request.Builder()
                    .url(deepSeekConfig.getBaseUrl() + "/chat/completions")
                    .addHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey())
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();
            
            // 发送请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    logger.info("DeepSeek API响应: {}", responseBody);
                    return JSON.parseObject(responseBody, DeepSeekResponse.class);
                } else {
                    logger.error("DeepSeek API请求失败: {}", response.code());
                    throw new RuntimeException("DeepSeek API请求失败: " + response.code());
                }
            }
            
        } catch (IOException e) {
            logger.error("调用DeepSeek API异常", e);
            throw new RuntimeException("调用DeepSeek API异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取AI回复内容
     * @param userMessage 用户消息
     * @param systemPrompt 系统提示词（可选）
     * @return AI回复的文本内容
     */
    public String getChatResponse(String userMessage, String systemPrompt) {
        DeepSeekResponse response = chat(userMessage, systemPrompt);
        if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
            return response.getChoices().get(0).getMessage().getContent();
        }
        return "抱歉，我无法为您提供回复。";
    }
    
    /**
     * 获取AI回复内容（无系统提示词）
     * @param userMessage 用户消息
     * @return AI回复的文本内容
     */
    public String getChatResponse(String userMessage) {
        return getChatResponse(userMessage, null);
    }
}
